
#include "auto_feed.h"
#if (COMPLIE_AUTO_FEED == 1)

void time_work_cb(cc_work *work, void *work_data);
struct timer_work
{
    cc_work work;
    void (*work_func)(struct cc_work *work, void *work_data);
    uint8_t is_used;
    int hour, min, sec;
    int set_weight;
};

struct timer_work time_works[3];
int timer_work_init()
{
    for (size_t i = 0; i < 3; i++)
    {
        cc_work_init(&time_works[0].work, time_work_cb, CC_NULL);
        time_works[0].is_used = 0;
    }

    return cc_true;
}
CC_INIT_APP_REGISTER(timer_work_init)

void time_work_cb(cc_work *work, void *work_data)
{
    cc_port_t mqtt_port = cc_port_init(CC_PORT_AUTO_FEED_MQTT, "feed_mqtt", 10, 50);
    cc_mnode_t node = cc_port_get_msg_node(mqtt_port, 1000);
    sprintf((char *)node->mem, "servo_open");
    cc_port_publish(mqtt_port, "servo_ctrl", node);
    // 24小时后再提交一次
    // TODO 记得考虑systick溢出
    cc_work_submit(work, 24 * 60 * 60 * 1000);
    return;
}

#if (CC_CONFIG_USE_MQTT && CC_CONFIG_USE_WIFI)
void auto_feed_time_mqtt_cb(char *topic, char *msg, int length, int topic_len)
{
    cc_port_t mqtt_port = cc_port_init(CC_PORT_AUTO_FEED_MQTT, "feed_mqtt", 10, 50);
    cc_port_set_state(mqtt_port, CC_PORT_STATE_CONN);
    int type = 0;
    int hour = 0, min = 0, sec = 0;
    int arg_cnt = cc_shell_parse_args(msg, "%d %d %d %d", &type, &hour, &min, &sec);
    cc_log("set time:%d %d %d\r\n", hour, min, sec);

    int now_tick = ((cc_hour) * 3600 * 100 + (cc_min) * 60 * 1000 + (cc_sec) * 1000);
    int delay_tick = ((hour) * 3600 * 100 + (min) * 60 * 1000 + (sec) * 1000);
    int delay_time = 0;
    if (now_tick > delay_tick)
    {
        delay_time = 24 * 60 * 60 * 10000 + (delay_tick - now_tick);
    }
    else
    {
        delay_time = delay_tick - now_tick;
    }
    int test_time = delay_time / 1000;
    if (type >= 0 && type <= 2)
    {
        if (time_works[type].is_used)
        {
            cc_work_cancel(&time_works[type].work);
        }
        else
        {
            time_works[type].is_used = 0;
        }
    }

    cc_log("delay time:%d next:%d %d %d \r\n", delay_time, test_time / 3600 % 24, test_time / 60 % 60, test_time % 60);
    cc_work_submit(&time_works[type].work, delay_time);
    return;
}
CC_TOPIC_SUBSRIBE_ALIAS(auto_feed_time_mqtt_cb, "cc_feed_time")
#endif
#endif